module Language.Coal.VariablesContext where

import Data.Map (Map)
import qualified Data.Map as Map

data VariablesContext a = Empty 
	| VC {parent :: VariablesContext a, current :: Map String a} deriving (Show)


insertVariable :: String -> a -> VariablesContext a -> VariablesContext a
insertVariable name t Empty = VC Empty (Map.singleton name t)
insertVariable name t c = VC (parent c) (Map.insert name t (current c))

memberVariable :: String -> VariablesContext a -> Bool
memberVariable name Empty = False
memberVariable name c = Map.member name (current c) || memberVariable name (parent c)

fromList :: [(String, a)] -> VariablesContext a
fromList l = insertVariableList l Empty

insertVariableList :: [(String, a)] -> VariablesContext a -> VariablesContext a
insertVariableList l c = foldl (flip $ uncurry insertVariable) c l

lookupVariable :: String -> VariablesContext a -> Maybe a
lookupVariable e Empty = Nothing 
lookupVariable n c = if Map.member n vi then Map.lookup n vi else lookupVariable n p where
	p = parent c
	vi = current c

child :: VariablesContext a -> VariablesContext a
child p = VC p Map.empty